﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace OF.Lib.DataAccess
{
    public class DEMapper
    {

        /// <summary>
        /// 使用DataTable填充列表
        /// </summary>
        /// <typeparam name="T">列表元素的实体类</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public List<T> FillEntityList<T>(DataTable dt) where T : class, new()
        {
            List<T> list = new List<T>();
            if (dt == null || dt.Rows.Count <= 0)
            {
                return list;
            }
            foreach (DataRow row in dt.Rows)
            {
                list.Add(FillEntity<T>(row));
            }
            return list;
        }

        /// <summary>
        /// 用DataRow填充实体类
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="dr">DataRow</param>
        /// <returns></returns>
        public T FillEntity<T>(DataRow dr) where T : class, new()
        {
            if (dr == null)
            {
                return default(T);
            }

            //T model = (T)Activator.CreateInstance(typeof(T));  
            T model = new T();

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                if (propertyInfo != null && dr[i] != DBNull.Value)
                {
                    propertyInfo.SetValue(model, dr[i], null);
                }
            }
            return model;
        }
 
    }
}
